package com.glowdayz.glowmee;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.util.SparseArrayCompat;
import android.support.v4.view.ViewPager;
import android.view.ContextThemeWrapper;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.glowdayz.common.ActivityManager;
import com.glowdayz.common.CDialog;
import com.glowdayz.common.PagerSlidingTabStrip;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.RegisterCMD;
import com.glowdayz.model.UserInfo;

public class ProfileHome extends FragmentActivity implements ScrollTabHolder, ViewPager.OnPageChangeListener {
	
	private ActivityManager am = ActivityManager.getInstance();

	private View mHeader;

	private PagerSlidingTabStrip mPagerSlidingTabStrip;
	private ViewPager mViewPager;
	private PagerAdapter mPagerAdapter;

	private int mMinHeaderHeight;
	private int mHeaderHeight;
	private int mMinHeaderTranslation;
	
	ImageView backUserImg = null, frontUserImg = null;
	TextView userNickName = null, userInfo = null;
	Bitmap bm = null;
	boolean isImage = false;
	
	TextView textTitle = null;
	ImageView okBt = null;
	
    int paramId = 0;
    
    String url = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		am.addActivity(this);

		mMinHeaderHeight = getResources().getDimensionPixelSize(R.dimen.min_header_height);
		mHeaderHeight = getResources().getDimensionPixelSize(R.dimen.header_height);
		mMinHeaderTranslation = -mMinHeaderHeight + 40;

		setContentView(R.layout.activity_profile_home);

		mHeader = findViewById(R.id.header);

		mPagerSlidingTabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setOffscreenPageLimit(4);


		mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
		mPagerAdapter.setTabHolderScrollingContent(this);

		mViewPager.setAdapter(mPagerAdapter);

		mPagerSlidingTabStrip.setViewPager(mViewPager);
		mPagerSlidingTabStrip.setOnPageChangeListener(this);
		
		okBt = (ImageView) findViewById(R.id.okBt);
		okBt.setImageResource(R.drawable.top_edit);
		okBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		okBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ProfileHome.this, EditProfile.class);
				startActivityForResult(intent, 1);
			}
		});
		
		ImageView backBt = (ImageView) findViewById(R.id.backBt);
		backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		backBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		textTitle = (TextView) findViewById(R.id.textTitle);
		textTitle.setText("나의 프로필");
		
		Intent fromIntent = getIntent();
		paramId = fromIntent.getIntExtra("PARAM_id", 0);
		
		backUserImg = (ImageView) findViewById(R.id.backUserImg);
		frontUserImg = (ImageView) findViewById(R.id.frontUserImg);
		userNickName = (TextView) findViewById(R.id.userNickName);
		userInfo = (TextView) findViewById(R.id.userInfo);
		
		if (paramId > 0) {
			url = getResources().getString(R.string.server_url) + "/glowmee/registerXml.do?id=" + paramId;
		} else {
			url = getResources().getString(R.string.server_url) + "/glowmee/registerXml.do?id=" + UserInfo.getInstance().getUSER_ID();
		}
		
		(new ProfileWorker()).execute();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == 1) {
				
				if (paramId > 0) {
					url = getResources().getString(R.string.server_url) + "/glowmee/registerXml.do?id=" + paramId;
				} else {
					url = getResources().getString(R.string.server_url) + "/glowmee/registerXml.do?id=" + UserInfo.getInstance().getUSER_ID();
				}
				
				(new ProfileWorker()).execute();
			}
		}
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// nothing
	}

	@Override
	public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
		// nothing
	}

	@Override
	public void onPageSelected(int position) {
		SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mPagerAdapter.getScrollTabHolders();
		ScrollTabHolder currentHolder = scrollTabHolders.valueAt(position);

		currentHolder.adjustScroll((int) (mHeader.getHeight() + mHeader.getTranslationY()));
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount, int pagePosition) {
		if (mViewPager.getCurrentItem() == pagePosition) {
			int scrollY = getScrollY(view);
			mHeader.setTranslationY(Math.max(-scrollY, mMinHeaderTranslation));
		}
	}

	@Override
	public void adjustScroll(int scrollHeight) {
		// nothing
	}

	public int getScrollY(AbsListView view) {
		View c = view.getChildAt(0);
		if (c == null) {
			return 0;
		}

		int firstVisiblePosition = view.getFirstVisiblePosition();
		int top = c.getTop();

		int headerHeight = 0;
		if (firstVisiblePosition >= 1) {
			headerHeight = mHeaderHeight;
		}

		return -top + firstVisiblePosition * c.getHeight() + headerHeight;
	}

	public static float clamp(float value, float max, float min) {
		return Math.max(Math.min(value, min), max);
	}

	public class PagerAdapter extends FragmentPagerAdapter {

		private SparseArrayCompat<ScrollTabHolder> mScrollTabHolders;
		private final String[] TITLES = { "Pick", "Like", "Wish", "Review" };
		private ScrollTabHolder mListener;

		public PagerAdapter(FragmentManager fm) {
			super(fm);
			mScrollTabHolders = new SparseArrayCompat<ScrollTabHolder>();
		}

		public void setTabHolderScrollingContent(ScrollTabHolder listener) {
			mListener = listener;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return TITLES[position];
		}

		@Override
		public int getCount() {
			return TITLES.length;
		}

		@Override
		public Fragment getItem(int position) {
			ScrollTabHolderFragment fragment = null;
			
			switch (position) {
			case 0:
				fragment = (ScrollTabHolderFragment) ProfilePickFm.newInstance(position, paramId);
				break;
			case 1:
				fragment = (ScrollTabHolderFragment) ProfileLikeFm.newInstance(position, paramId);
				break;
			case 2:
				fragment = (ScrollTabHolderFragment) ProfileWishFm.newInstance(position, paramId);
				break;
			case 3:
				fragment = (ScrollTabHolderFragment) ProfileReviewFm.newInstance(position, paramId);
				break;
			}
			
			mScrollTabHolders.put(position, fragment);
			if (mListener != null) {
				fragment.setScrollTabHolder(mListener);
			}

			return fragment;
		}

		public SparseArrayCompat<ScrollTabHolder> getScrollTabHolders() {
			return mScrollTabHolders;
		}

	}
	
	public class ProfileWorker extends AsyncTask<Object, RegisterCMD, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(ProfileHome.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idRegister = 0;
				String eMail = null;
				String nickName = null;
				int birthYear = 0;
				String skinTypeValue = null;
				String genderValue = null;
				String locationValue1 = null;
				String locationValue2 = null;
				String userTel = null;
				String userAddress = null;
				String thumbnail = null;
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("idRegister")) {
							parser.next();
							idRegister = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("eMail")) {
							parser.next();
							eMail = parser.getText();
						} else if (tag.equals("nickName")) {
							parser.next();
							nickName = parser.getText();
						} else if (tag.equals("birthYear")) {
							parser.next();
							birthYear = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("skinTypeValue")) {
							parser.next();
							skinTypeValue = parser.getText();
						} else if (tag.equals("genderValue")) {
							parser.next();
							genderValue = parser.getText();
						} else if (tag.equals("locationValue1")) {
							parser.next();
							locationValue1 = parser.getText();
						} else if (tag.equals("locationValue2")) {
							parser.next();
							locationValue2 = parser.getText();
						} else if (tag.equals("userTel")) {
							parser.next();
							userTel = parser.getText();
						} else if (tag.equals("userAddress")) {
							parser.next();
							userAddress = parser.getText();
						} else if (tag.equals("thumbnail")) {
							parser.next();
							thumbnail = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("item")) {
							RegisterCMD item = new RegisterCMD(idRegister, eMail, nickName, locationValue1, locationValue2,
									birthYear, skinTypeValue, genderValue, thumbnail, userTel, userAddress);
							if (thumbnail != null) {
								try {
									URL url2 = new URL(getResources().getString(R.string.server_url) + item.getCreate_date().trim()); 
									URLConnection conn = url2.openConnection(); 
									conn.connect(); 
									BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); 
									bm = BitmapFactory.decodeStream(bis); 
									bis.close();
									isImage = true;
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
							
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(RegisterCMD... param) {
			userNickName.setText(param[0].getNickName());
			
			if (paramId > 0 && paramId != UserInfo.getInstance().getUSER_ID()) {
				textTitle.setText(param[0].getNickName() + "님의 프로필");
				okBt.setVisibility(View.GONE);
			}
			
			userNickName.setTextAppearance(getApplicationContext(), R.style.AudioFileInfoOverlayText);
			userNickName.setTextSize(22);
			if (param[0].getSkinTypeValue().equals("null") && param[0].getBirthYear() != 0) {
				int age = Calendar.getInstance().get(Calendar.YEAR) - param[0].getBirthYear() + 1;
				userInfo.setText(age + "세");
			} else if (!param[0].getSkinTypeValue().equals("null") && param[0].getBirthYear() == 0) {
				userInfo.setText(param[0].getSkinTypeValue() + "피부");
			} else if (!param[0].getSkinTypeValue().equals("null") && param[0].getBirthYear() != 0) {
				int age = Calendar.getInstance().get(Calendar.YEAR) - param[0].getBirthYear() + 1;
				userInfo.setText(age + "세 " + param[0].getSkinTypeValue() + "피부");
			}
			userInfo.setTextAppearance(getApplicationContext(), R.style.AudioFileInfoOverlayText);
			if (isImage) {
				backUserImg.setImageBitmap(fastblur(bm, 10));
				frontUserImg.setImageBitmap(bm);
			} else {
				backUserImg.setImageDrawable(null);
			}
			
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ProfileHome.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new ProfileWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	public Bitmap fastblur(Bitmap sentBitmap, int radius) {

        // Stack Blur v1.0 from
        // http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
        //
        // Java Author: Mario Klingemann <mario at quasimondo.com>
        // http://incubator.quasimondo.com
        // created Feburary 29, 2004
        // Android port : Yahel Bouaziz <yahel at kayenko.com>
        // http://www.kayenko.com
        // ported april 5th, 2012

        // This is a compromise between Gaussian Blur and Box blur
        // It creates much better looking blurs than Box Blur, but is
        // 7x faster than my Gaussian Blur implementation.
        //
        // I called it Stack Blur because this describes best how this
        // filter works internally: it creates a kind of moving stack
        // of colors whilst scanning through the image. Thereby it
        // just has to add one new block of color to the right side
        // of the stack and remove the leftmost color. The remaining
        // colors on the topmost layer of the stack are either added on
        // or reduced by one, depending on if they are on the right or
        // on the left side of the stack.
        //
        // If you are using this algorithm in your code please add
        // the following line:
        //
        // Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>

        Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = ( 0xff000000 & pix[yi] ) | ( dv[rsum] << 16 ) | ( dv[gsum] << 8 ) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }
        bitmap.setPixels(pix, 0, w, 0, 0, w, h);

        return (bitmap);
	}
	
    @Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}
}
